package com.suns.controller.interceptor;

import com.suns.controller.AdminController;
import com.suns.controller.UserController;
import com.suns.domain.Admin;
import com.suns.domain.User;
import com.suns.util.CookieUtil;
import com.suns.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;

    @Override //拦截原始操作执行之前执行的代码
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从redis缓存中获取用户信息
        String token = UserController.gettoken(request);
        if (token != null) {
            String json = CookieUtil.decrypt(redisUtil.get(token), "cookie_key");
            User user = User.fromJsonString(json);
            if (user != null) {
                return true;
            }
        }
        response.sendRedirect("/users/autologin");
        return false;
    }
}
